﻿using UnityEngine;
using System.Collections.Generic;
using Dict.Blo;
using Dict.DataModel;
using ProtoBuf.Message;
namespace UI
{
    public class UIStoryData
    {
        public List<string> completeQuestIds = new List<string>();

        private string curQuestId = "quest_1";

        private int lastQuestCount;
        /// <summary>
        /// 登录时初始化
        /// </summary>
        /// <param name="quests"></param>
        public void Init(List<string> quests)
        {
            completeQuestIds.Clear();
            foreach(var questId in quests)
            {
                if(DictStoryBlo.GetQuest(questId)!=null)
                {
                    completeQuestIds.Add(questId);
                }
            }
            RefreshCurQuest();
        }
        /// <summary>
        /// 当前正在执行的任务
        /// </summary>
        /// <returns></returns>
        public string GetCurQuestId()
        {
            if(lastQuestCount!=completeQuestIds.Count)
            {
                RefreshCurQuest();
            }
            return curQuestId;
        }
        /// <summary>
        /// 完成了新的任务
        /// </summary>
        /// <param name="newQuestId"></param>
        public void AddFinishQuest(string newQuestId)
        {
            if(!completeQuestIds.Contains(newQuestId))
            {
                completeQuestIds.Add(newQuestId);
            }
            RefreshCurQuest();
            //lastQuestCount = completeQuestIds.Count;

            //if (curQuestId == null)
            //{
            //    curQuestId = newQuestId;
            //}

            //var curQuestData = DictStoryBlo.GetQuest(curQuestId);
            //var newQuestData = DictStoryBlo.GetQuest(newQuestId);

            //if (curQuestData.order <= (newQuestData.order + 1))
            //{
            //    curQuestId = DictStoryBlo.GetQuest(curQuestData.order+1).questId;
            //}
        }
        /// <summary>
        /// 任务是否已经完成
        /// </summary>
        /// <param name="questId"></param>
        /// <returns></returns>
        public bool isQuestFinished(string questId)
        {
            return completeQuestIds.Contains(questId);
        }
        /// <summary>
        /// 刷新当前任务
        /// </summary>
        private void RefreshCurQuest()
        {
            int maxOrder = -1;
            for(int i=0;i<completeQuestIds.Count;i++)
            {
                var questData = DictStoryBlo.GetQuest(completeQuestIds[i]);
                if (questData != null)
                {
                    maxOrder = Mathf.Max(maxOrder, questData.order);
                }
            }
            maxOrder = maxOrder == -1 ? 0:maxOrder;
            curQuestId = DictStoryBlo.GetQuest(maxOrder + 1).questId;
            lastQuestCount = completeQuestIds.Count;
        }

    }
}